<template>
  <div class="import-data-container">
    <div class="empty-data-box">
      <div class="empty-content">
        <img src="@/assets/images/import-empty.png" alt="暂无数据" class="empty-image" />
        <div class="empty-text">您未导入数据，请先导入数据，再进行分析</div>
        <el-button type="primary" @click="showImportDialog">导入数据</el-button>
      </div>
    </div>

    <!-- 导入数据弹窗 -->
    <ElDialog v-model="importDialogVisible" title="导入数据" width="500px" destroy-on-close>
      <div class="import-dialog-content">
        <ElUpload
          class="upload-wrapper"
          drag
          action="#"
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          accept=".xls,.xlsx"
        >
          <ElIcon class="upload-icon">
            <Icon icon="vi-ep:upload-filled" />
          </ElIcon>
          <div class="upload-text">
            <span>将文件拖到此处，或<em>点击上传</em></span>
            <div class="upload-tip">支持 .xls, .xlsx 格式文件</div>
          </div>
        </ElUpload>

        <div class="import-actions">
          <a href="#" @click="downloadTemplate" class="template-link">
            <Icon icon="vi-ep:download" class="mr-5px" />
            下载导入模板
          </a>
          <div class="action-buttons">
            <ElButton @click="importDialogVisible = false">取 消</ElButton>
            <ElButton type="primary" @click="handleImport" :loading="importing"> 导 入 </ElButton>
          </div>
        </div>
      </div>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElDialog, ElButton, ElUpload, ElIcon } from 'element-plus'
import { useRouter } from 'vue-router'
import { importData, downloadTemplate as downloadTemplateApi } from '@/api/electricityAbnormal'

// 获取路由实例
const router = useRouter()

// 导入对话框可见性
const importDialogVisible = ref(false)
const importing = ref(false)
const selectedFile = ref<File | null>(null)

// 打开导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true
  selectedFile.value = null
}

// 文件变更处理
const handleFileChange = (file: any) => {
  const isExcel =
    file.raw.type === 'application/vnd.ms-excel' ||
    file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件！')
    return false
  }

  selectedFile.value = file.raw
  return true
}

// 文件移除处理
const handleFileRemove = () => {
  selectedFile.value = null
}

// 下载模板
const downloadTemplate = async (event: Event) => {
  event.preventDefault()
  event.stopPropagation()

  try {
    ElMessage.info('正在下载模板...')

    // 调用下载API
    const res = await downloadTemplateApi()

    // 处理二进制数据
    const blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = '电费数据导入模板.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('模板下载失败:', error)
    ElMessage.error('模板下载失败，请重试')
  }
}

// 导入处理
const handleImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }

  importing.value = true

  try {
    // 创建FormData
    const formData = new FormData()
    formData.append('file', selectedFile.value)

    // 调用API上传
    const res = await importData(formData)
    console.log('导入响应:', res)

    // 处理响应

    if (res && res.success == true) {
      ElMessage.success(`成功导入数据`)
      importDialogVisible.value = false

      // 导入成功后延迟跳转到电费异常智能识别页面
      setTimeout(() => {
        router.push('/electricityAbnormal')
      }, 1500)
    } else {
      ElMessage.error(res?.data?.msg || res?.data?.message || '导入失败，请检查文件格式是否正确')
    }
  } catch (error) {
    console.error('导入处理出错:', error)
    ElMessage.error('导入处理出错，请重试')
  } finally {
    importing.value = false
  }
}
</script>

<style scoped>
.import-data-container {
  padding: 20px;
  height: 100%;
  background-color: #f5f7fa;
}

.empty-data-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80vh;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-image {
  width: 400px;
  height: 400px;
  /* margin-bottom: 20px; */
}

.empty-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 30px;
}

/* 添加导入弹窗相关样式 */
.import-dialog-content {
  padding: 20px;
}

.upload-wrapper {
  width: 100%;
  margin-bottom: 20px;
}

.upload-icon {
  font-size: 40px;
  color: #409eff;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.import-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.template-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.template-link:hover {
  color: #66b1ff;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>
